Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | export const dynamic = "force-dynamic"; import { NextRequest, NextResponse } from 'next/server'; import { } from "next-auth"; import { prisma } from "@/lib/prisma"; import { logger } from "@/lib/logging"; import { updatePromotionSchema } from "@/lib/promotions/validators"; import { withAdmin, withErrorHandling, successResponse, ApiError, ApiSuccessResponse, ApiErrorResponse } from "@/lib/api"; import { RouteContext } from "@/lib/api/middleware"; interface RouteParams { params: Promise<{ id: string }>; } /** * GET /api/admin/promotions/[id] * Get a single promotion with all details */ async function handleGet(_request: NextRequest, context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> { const { id } = await (context as RouteParams).params; const promotionId = parseInt(id); if (isNaN(promotionId)) { throw ApiError.badRequest("Invalid promotion ID"); } const promotion = await prisma.promotion.findUnique({ where: { id: promotionId }, include: { codes: true, targetProducts: { include: { product: { select: { id: true, title: true, price: true } } } }, targetCategories: { include: { category: { select: { id: true, title: true } } } }, conditions: true, usages: { take: 50, orderBy: { usedAt: "desc" }, include: { user: { select: { id: true, name: true, email: true } }, order: { select: { id: true, total: true } }, promoCode: { select: { code: true } } } }, bogoConfig: { include: { getProduct: { select: { id: true, title: true } }, getCategory: { select: { id: true, title: true } } } }, bundleConfig: { include: { products: { include: { product: { select: { id: true, title: true, price: true } } } } } }, freeGiftConfig: { include: { giftProduct: { select: { id: true, title: true, price: true } } } }, tieredConfig: { include: { tiers: { orderBy: { minQuantity: "asc" } } } }, flashSaleConfig: true, _count: { select: { usages: true, codes: true } } } }); if (!promotion) { throw ApiError.notFound("Promotion"); } // Compute status const now = new Date(); let computedStatus: "active" | "inactive" | "expired" | "scheduled" = "inactive"; if (!promotion.isActive) { computedStatus = "inactive"; } else if (new Date(promotion.endDate) < now) { computedStatus = "expired"; } else if (new Date(promotion.startDate) > now) { computedStatus = "scheduled"; } else { computedStatus = "active"; } return successResponse({ ...promotion, computedStatus, usageCount: promotion._count.usages, codesCount: promotion._count.codes }); } /** * PUT /api/admin/promotions/[id] * Update a promotion */ async function handlePut(request: NextRequest, context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> { const { id } = await (context as RouteParams).params; const promotionId = parseInt(id); if (isNaN(promotionId)) { throw ApiError.badRequest("Invalid promotion ID"); } const body = await request.json(); body.id = promotionId; // Validate input const validationResult = updatePromotionSchema.safeParse(body); if (!validationResult.success) { throw ApiError.validation("Validation failed", validationResult.error.issues); } const data = validationResult.data; // Check if promotion exists const existing = await prisma.promotion.findUnique({ where: { id: promotionId } }); if (!existing) { throw ApiError.notFound("Promotion"); } // Update promotion and related data in a transaction await prisma.$transaction(async (tx) => { // Update main promotion fields await tx.promotion.update({ where: { id: promotionId }, data: { name: data.name, displayName: data.displayName, description: data.description, type: data.type, discountType: data.discountType, discountValue: data.discountValue, startDate: data.startDate, endDate: data.endDate, isActive: data.isActive, usageLimit: data.usageLimit, perCustomerLimit: data.perCustomerLimit, minimumPurchase: data.minimumPurchase, maximumDiscount: data.maximumDiscount, targetType: data.targetType, stackable: data.stackable, priority: data.priority } }); // Update target products if provided if (data.targetProductIds !== undefined) { await tx.promotionProduct.deleteMany({ where: { promotionId } }); if (data.targetProductIds.length > 0) { await tx.promotionProduct.createMany({ data: data.targetProductIds.map((productId) => ({ promotionId, productId })) }); } } // Update target categories if provided if (data.targetCategoryIds !== undefined) { await tx.promotionCategory.deleteMany({ where: { promotionId } }); if (data.targetCategoryIds.length > 0) { await tx.promotionCategory.createMany({ data: data.targetCategoryIds.map((categoryId) => ({ promotionId, categoryId })) }); } } // Update conditions if provided if (data.conditions !== undefined) { await tx.promotionCondition.deleteMany({ where: { promotionId } }); if (data.conditions.length > 0) { await tx.promotionCondition.createMany({ data: data.conditions.map((condition) => ({ promotionId, conditionType: condition.conditionType, operator: condition.operator, value: condition.value })) }); } } // Update BOGO config if provided if (data.bogoConfig !== undefined) { await tx.bogoPromotion.deleteMany({ where: { promotionId } }); if (data.bogoConfig) { await tx.bogoPromotion.create({ data: { promotionId, buyQuantity: data.bogoConfig.buyQuantity, getQuantity: data.bogoConfig.getQuantity, getProductId: data.bogoConfig.getProductId, getCategoryId: data.bogoConfig.getCategoryId, discountPercent: data.bogoConfig.discountPercent ?? 100 } }); } } // Update bundle config if provided if (data.bundleConfig !== undefined) { const existingBundle = await tx.bundlePromotion.findUnique({ where: { promotionId } }); if (existingBundle) { await tx.bundleProduct.deleteMany({ where: { bundleId: existingBundle.id } }); await tx.bundlePromotion.delete({ where: { promotionId } }); } if (data.bundleConfig) { const bundle = await tx.bundlePromotion.create({ data: { promotionId, bundlePrice: data.bundleConfig.bundlePrice } }); if (data.bundleConfig.products && data.bundleConfig.products.length > 0) { await tx.bundleProduct.createMany({ data: data.bundleConfig.products.map((product) => ({ bundleId: bundle.id, productId: product.productId, quantity: product.quantity })) }); } } } // Update free gift config if provided if (data.freeGiftConfig !== undefined) { await tx.freeGiftPromotion.deleteMany({ where: { promotionId } }); if (data.freeGiftConfig) { await tx.freeGiftPromotion.create({ data: { promotionId, giftProductId: data.freeGiftConfig.giftProductId, giftQuantity: data.freeGiftConfig.giftQuantity ?? 1 } }); } } // Update tiered config if provided if (data.tieredConfig !== undefined) { const existingTiered = await tx.tieredPromotion.findUnique({ where: { promotionId } }); if (existingTiered) { await tx.promotionTier.deleteMany({ where: { tieredPromotionId: existingTiered.id } }); await tx.tieredPromotion.delete({ where: { promotionId } }); } if (data.tieredConfig) { const tiered = await tx.tieredPromotion.create({ data: { promotionId } }); if (data.tieredConfig.tiers && data.tieredConfig.tiers.length > 0) { await tx.promotionTier.createMany({ data: data.tieredConfig.tiers.map((tier) => ({ tieredPromotionId: tiered.id, minQuantity: tier.minQuantity, discountType: tier.discountType, discountValue: tier.discountValue })) }); } } } // Update flash sale config if provided if (data.flashSaleConfig !== undefined) { await tx.flashSale.deleteMany({ where: { promotionId } }); if (data.flashSaleConfig) { await tx.flashSale.create({ data: { promotionId, headline: data.flashSaleConfig.headline, subheadline: data.flashSaleConfig.subheadline, bannerImage: data.flashSaleConfig.bannerImage, countdown: data.flashSaleConfig.countdown ?? true } }); } } }); // Fetch updated promotion const updated = await prisma.promotion.findUnique({ where: { id: promotionId }, include: { codes: true, targetProducts: { include: { product: { select: { id: true, title: true } } } }, targetCategories: { include: { category: { select: { id: true, title: true } } } }, conditions: true, bogoConfig: true, bundleConfig: { include: { products: { include: { product: { select: { id: true, title: true } } } } } }, freeGiftConfig: { include: { giftProduct: { select: { id: true, title: true } } } }, tieredConfig: { include: { tiers: true } }, flashSaleConfig: true } }); logger.info("Promotion updated", { category: 'API', promotionId, name: data.name }); return successResponse(updated); } /** * DELETE /api/admin/promotions/[id] * Delete a promotion */ async function handleDelete(request: NextRequest, context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> { const { id } = await (context as RouteParams).params; const promotionId = parseInt(id); if (isNaN(promotionId)) { throw ApiError.badRequest("Invalid promotion ID"); } // Check if promotion exists const existing = await prisma.promotion.findUnique({ where: { id: promotionId }, include: { _count: { select: { usages: true } } } }); if (!existing) { throw ApiError.notFound("Promotion"); } // Warn if promotion has been used if (existing._count.usages > 0) { const forceDelete = request.nextUrl.searchParams.get("force") === "true"; if (!forceDelete) { throw ApiError.badRequest( `This promotion has been used ${existing._count.usages} times. Add ?force=true to delete anyway.` ); } } await prisma.promotion.delete({ where: { id: promotionId } }); logger.info("Promotion deleted", { category: 'API', promotionId, name: existing.name }); return successResponse({ message: "Promotion deleted successfully" }); } export const GET = withErrorHandling(withAdmin(handleGet)); export const PUT = withErrorHandling(withAdmin(handlePut)); export const DELETE = withErrorHandling(withAdmin(handleDelete)); |